import { Component } from 'react';
import WithRouter from '@/router/WithRouter'
import { getGoodsInfo, getLikeGoods, addCartGoods } from '@/Api/info';
import InfoSwiper from '../../components/Info/InfoSwiper';
import { Skeleton, Tabs, ActionBar, Popup, Stepper, Cell, ImagePreview, Toast } from 'react-vant';
import './info.less'
import GoodsInfo from '../../components/Info/goodsInfo';
import Guige from '../../components/Info/guige';
import Like from '../../components/Info/like';
import { CartO, StarO, ArrowLeft, Ellipsis } from '@react-vant/icons'
import { getPreOrderNum } from '@/Api/order'
import {connect} from 'react-redux'
import { getCartListAction } from '../../redux/action/cartAciton';
class Info extends Component {
    state = {
        sliderImage: [],
        isShow: true,
        goodsInfo: {
            price: 0,
            goodsName: "",
            otprice: 0,
            sales: 0,
            stock: 0,
            image: "",
            skuId: 0,
            productId: 0
        },
        likeList: [],
        content: "",
        visible: false,
        // 商品属性列表
        productAttr: [],
        // 商品规格所对应的详情
        productValue: null,
        // 定义空数组用来记录当前所点击的属性索引以及属性值的索引
        sel: [],
        goodsName: "",
        // 当前选中得商品规格名称
        skuName: "",
        imgList: [],
        // 商品数量；
        num: 1
    }
    render() {
        let { sliderImage, isShow, goodsInfo, likeList, content, visible, productAttr, sel, skuName, num } = this.state;
        return (
            <Skeleton rowHeight={[70, 20, 20, 20, 20, 20]} rowWidth={["100%", "100%", "100%", "100%", "100%", "100%"]} row={6} loading={isShow} animate={true} title={true} titleWidth='100%' round={false}>
                <div className='myinfo'>
                    <Tabs
                        sticky
                        scrollspy={{ autoFocusLast: true, reachBottomThreshold: 50 }}
                        defaultActive='goods'
                    >
                        <Tabs.TabPane name={'goods'} title={`商品`}>
                            <div>
                                <InfoSwiper sliderImage={sliderImage}></InfoSwiper>
                            </div>
                            <div>
                                <GoodsInfo goodsInfo={goodsInfo}></GoodsInfo>
                            </div>
                            <div>
                                <Guige open={() => {
                                    this.setState({
                                        visible: true
                                    })
                                }} skuName={skuName}></Guige>
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane name={'pingjia'} title={`评价`}>
                            <div className='pingjia'>
                                <div>用户评价</div>
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane name={'tuijian'} title={`推荐`}>
                            <div>
                                <Like likeList={likeList}></Like>
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane name={'xiangqing'} title={`详情`}>
                            <div>
                                <div className='title'>商品详情</div>
                                <div dangerouslySetInnerHTML={{
                                    __html: content
                                }} onClick={(e) => this.showImg(e)}></div>
                            </div>
                        </Tabs.TabPane>
                    </Tabs>
                    <ActionBar>
                        <ActionBar.Icon icon={<CartO />} badge={{ content:this.props.cartReducer.cartList.length}} text='购物车' />
                        <ActionBar.Icon icon={<StarO />} text='收藏' />
                        <ActionBar.Button type='warning' text='加入购物车' onClick={() => {
                            this.setState({
                                visible: true
                            })
                        }} />
                        <ActionBar.Button type='danger' text='立即购买' onClick={() => {
                            this.setState({
                                visible: true
                            })
                        }} />
                    </ActionBar>
                    <div className='navTop'>
                        <div onClick={() => {
                            this.props.router.navigate(-1)
                        }}>
                            <ArrowLeft />
                        </div>
                        <div>
                            <Ellipsis />
                        </div>
                    </div>
                    <Popup
                        visible={visible}
                        closeable
                        style={{ height: '70%' }}
                        position='bottom'
                        round
                        onClose={() => {
                            this.setState({
                                visible: false
                            })
                        }}
                    >
                        <div className='goodsSku'>
                            <div className='skuheader'>
                                <div className='headerleft'>
                                    <img src={goodsInfo.image} alt="" />
                                </div>
                                <div className='headerright'>
                                    <div className='skugoodsname'>
                                        {goodsInfo.goodsName}
                                    </div>
                                    <div className='skuprice'>
                                        ￥{goodsInfo.price}
                                    </div>
                                    <div className='skustock'>
                                        库存：{goodsInfo.stock}
                                    </div>
                                </div>
                            </div>
                            {
                                productAttr.map((item, i) => {

                                    return (
                                        <div key={item.id}>
                                            <div className='attrTitle'>{item.attrName}</div>
                                            <div className='attrValues'>
                                                {
                                                    item.attrValues.map((values, index) => {
                                                        return <div key={index} className={sel[i] === index ? 'values activeValues' : 'values'} onClick={() => this.changeSku(i, index)}>{values}</div>
                                                    })
                                                }
                                            </div>
                                        </div>
                                    )
                                })
                            }
                            <Cell title='数量' center>
                                <Stepper
                                    value={num}
                                    theme='round'
                                    min={1}
                                    buttonSize='22'
                                    disableInput
                                    onChange={(value) => {
                                        this.setState({
                                            num: value
                                        })
                                    }}
                                />
                            </Cell>
                        </div>
                        <ActionBar>
                            <ActionBar.Icon icon={<CartO />} badge={{ content: this.props.cartReducer.cartList.length}} text='购物车' />
                            <ActionBar.Icon icon={<StarO />} text='收藏' />
                            <ActionBar.Button type='warning' text='加入购物车' onClick={() => this.addCart()} />
                            <ActionBar.Button type='danger' text='立即购买' onClick={() => this.buyNow()} />
                        </ActionBar>
                    </Popup>
                </div>
            </Skeleton>
        )
    }
    // 组件渲染后发送请求获取商品详情
    async componentDidMount() {
        //  判断redux中cartlist是否为空若为空请求cartList
        console.log(  this.props)
        let cartList = this.props.cartReducer.cartList;
        if(cartList.length ===0){
            this.props.dispatch(getCartListAction())
        }
         this.$plusReady(()=>{
            plus.navigator.setStatusBarBackground("#fff");
            plus.navigator.setStatusBarStyle("dark");
        })
        // 获取动态路由动态参数（商品id）;
        let { id } = this.props.router.params;
        let res = await getGoodsInfo(id);
        // 获取商品详情
        let info = res.data.data.productInfo;
        // 处理商品属性值
        res.data.data.productAttr.forEach(item => {
            item.attrValues = item.attrValues.split(",")
        })
        // 处理商品详情获取 商品详情图片地址列表
        let imgList = [];
        info.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
            imgList.push(capture);
        });
        this.setState({
            sliderImage: JSON.parse(info.sliderImage),
            goodsName: info.storeName,
            content: info.content,
            productAttr: res.data.data.productAttr,
            productValue: res.data.data.productValue,
            imgList: imgList
        }, () => {
            this.getAttrDefaultIndex();
        })
        this.getLikeList();
        // 监听页面滚动
        window.onscroll = () => {
            // 获取屏幕宽
            let sw = document.documentElement.clientWidth;
            //获取滚动的距离
            let top = document.documentElement.scrollTop;

            let dom = document.querySelector(".rv-sticky")
            if (top >= sw) {
                dom.style.display = 'block'
            } else {
                dom.style.display = 'none'
            }
        }
    }
    // 获取优品推荐列表
    async getLikeList() { 
        let res = await getLikeGoods();
        let list = res.data.data.list;
        // 处理数据 将一维数组转化为二维数组；
        // 计算二位数组的个数
        let num = Math.ceil(list.length / 6);
        let likeList = [];
        for (let i = 0; i < num; i++) {
            console.log(i)
            if (i === (num - 1)) {
                likeList[i] = list.slice(i * 6)
            } else {
                likeList[i] = list.slice(i * 6, 6)
            }
        }
        this.setState({
            likeList: likeList,
            isShow: false,
        })
    }
    componentWillUnmount() {
        console.log(12312312)
        // 清楚监听事件
        window.onscroll = null;
    }
    // 初始化计算商品属性所对应的默认索引
    getAttrDefaultIndex() {
        // 获取属性列表
        let { productAttr } = this.state;
        // console.log(productAttr)
        // 用来存放属性所对应的默认值
        let newSel = [];
        productAttr.forEach((item, index) => {
            newSel[index] = 0
        })
        this.setState({
            sel: newSel
        }, () => {
            this.getSkuName();
        })
    }
    changeSku(i, index) {
        // i 表示当前点击的属性名所对应的索引
        // index 表示当前点击的属性所对应属性值得索引
        this.state.sel[i] = index;
        this.setState({
            sel: this.state.sel
        }, () => {
            this.getSkuName();
        })
    }
    // 计算获取当前选中得商品规格名称
    getSkuName() {
        let { sel, productAttr, productValue, goodsName } = this.state;
        let AttrList = [];
        sel.forEach((item, index) => {
            // item 属性值得索引
            // index 属性得索引
            // 获取每个属性选中得属性值名称
            let name = productAttr[index].attrValues[item];
            AttrList.push(name)
        })
        let SkuName = AttrList.join(",");
        // 根据商品规格名称获取当前商品规格详细商品数据；
        let SkuInfo = productValue[SkuName];
        this.setState({
            goodsInfo: {
                price: SkuInfo.price,
                goodsName: goodsName,
                otprice: SkuInfo.otPrice,
                sales: SkuInfo.sales,
                stock: SkuInfo.stock,
                image: SkuInfo.image,
                skuId: SkuInfo.id,
                productId: SkuInfo.productId
            },
            skuName: SkuName
        })
    }
    //图片预览
    showImg(e) {
        // console.log(e);
        // 获取当前点击得图片地址
        let src = e.target.currentSrc;
        // 根据当前点击的图片地址找到其所以对应得索引
        let index = this.state.imgList.findIndex(item => {
            return item === src
        })
        console.log(src)
        ImagePreview.open({
            images: this.state.imgList,
            startPosition: index
        })
    }
    // 加入购物车
    async addCart() {
        let { num, goodsInfo } = this.state;
        let data = {
            cartNum: num,
            isNew: false,
            productAttrUnique: goodsInfo.skuId,
            productId: goodsInfo.productId
        }
        // 发送请求加入购物车
        let res = await addCartGoods(data);
        console.log(res)
        if (res.data.code === 200) {
            Toast.success("加入成功")
            this.setState({
                visible: false
            })
        } else {
            Toast(res.data.message)
        }
    }
    // 立即购买生成订单号
    async buyNow() {
        let { goodsInfo, num } = this.state;
        // 获取请求参数
        let data = {
            orderDetails: [
                {
                    attrValueId: goodsInfo.skuId,
                    productId: goodsInfo.productId,
                    productNum: num
                }
            ],
            preOrderType: "buyNow"
        }
        let res = await getPreOrderNum(data);
        if(res.data.code!==200){
            return
        }
        this.props.router.navigate("/confrimorder", {
            state: {
                preOrderNo: res.data.data.preOrderNo
            }
        });
    }
}
export default connect((state)=>{
    return state
})( WithRouter(Info));
